package com.itheima.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.TokenHolder;
import com.itheima.domain.Employee;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * date: 2022/5/18 18:57
 *
 * @author daya000
 */

//继承拦截器
public class AuthInterceptor implements HandlerInterceptor {

    //使用redis
    private RedisTemplate<Object, Object> redisTemplate;

    public AuthInterceptor() {
    }

    public AuthInterceptor(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //拦截前要做什么事情
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //return false 不能往下放行
        //return true 准许往下执行

        //获取token的值
        String token = request.getHeader("Authorization");

        //判断访问网址的时候有没有携带token
        if (StrUtil.isNotEmpty(token)){
            //从token里面获取key
            Object redisObject = redisTemplate.opsForValue().get(token);

            if (Objects.nonNull(redisObject)){
                //从redis里面取出来的value是字符串，在json.parseobject转为实体类
                Employee employee = JSON.parseObject((String) redisObject, Employee.class);
                //判断这个实体类是否为空
                if (Objects.nonNull(employee)){

                    //获取这个用户id
                    String id = employee.getId();

                    // 写入ThreadLocal,获取当前操作用户的id,他存储到线程里面
                    TokenHolder.setCurrentId(id);

                    return true;
                }
            }

        }

        return false;

    }
    //拦截时要做什么事情
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    //拦截后要做什么事情
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
